package com.tensquare.user.interceptor;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WF on 2020/10/24 11:03
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到请求头
        String header = request.getHeader("Authorization");
        //2.判断是否有值，
        if(StrUtil.isNotBlank(header)){
            //2.1)得到token信息
            String token = header.substring(7);
            //2.2)如果存在，就解析token
            if(StrUtil.isNotBlank(token)){
                Claims claims = jwtUtil.parseJWT(token);
                //2.3)判断是否存在，如果存在，就放到请求作用域中
                if(claims != null){
                    request.setAttribute("claims",claims);
                }
            }
        }
        return true;
    }
}
